package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.DamageListGoodsMapper;

import com.atguigu.jxc.dao.GoodsMapper;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.atguigu.jxc.service.LogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DamageListGoodsServiceImpl extends ServiceImpl<DamageListGoodsMapper, TDamageListGoods> implements DamageListGoodsService {


    @Autowired
    private LogService logService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DamageListGoodsMapper damageListGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public ServiceVO save(DamageList damageList, String damageListGoodsStr) {
        // 使用谷歌Gson将JSON字符串数组转换成具体的集合
        Gson gson = new Gson();

        List<TDamageListGoods> damageListGoodsList = gson.fromJson(damageListGoodsStr,new TypeToken<List<TDamageListGoods>>(){}.getType());

        // 设置当前操作用户
        User currentUser = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());

        damageList.setUserId(currentUser.getUserId());

        // 保存商品报损单信息
        damageListGoodsMapper.saveDamageList(damageList);

        // 保存商品报损单商品信息
        for(TDamageListGoods damageListGoods : damageListGoodsList){

            damageListGoods.setDamageListId(damageList.getDamageListId());

            damageListGoodsMapper.saveDamageListGoods(damageListGoods);

            // 修改商品库存，状态
            Goods goods = goodsMapper.findByGoodsId(damageListGoods.getGoodsId());

            goods.setInventoryQuantity(goods.getInventoryQuantity()-damageListGoods.getGoodsNum());

            goods.setState(2);

            goodsMapper.updateGoods(goods);

        }

        // 保存日志
        logService.save(new Log(Log.INSERT_ACTION, "新增商品报损单："+damageList.getDamageNumber()));

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}
